<template>
  <div>
    <!-- 入口文件 -->
    <VFormRender :form-json="formJson"
                 :form-data="formData"
                 :parent-api="parentApi"
                 :option-data="optionData"
                 ref="vFormRef"/>
    <!-- 弹窗配置 -->
    <component v-if="layerNameKey!=null"
               :is="layerNameKey"
               :visible="hasCallShow"
               :info="msgWinData"
               :check-list="msgWinData.checkList"
    />
    <!-- 暂停接诊 -->
    <business-win-info :info="pauseLayerInfo.info" :visible="pauseLayerInfo.visible"></business-win-info>
  </div>

</template>

<script>
import VFormRender from "@c/public/form-render/index.vue";
import {setRem2} from "@/utils/rem.js";
import {AndroidSDK} from "@/sdk/AndroidSdkService";
import {resetLongToStr} from "@/utils/biz/common/BizUtils";
import {SubjectUtil} from "@/utils/observer/SubjectUtil";
import {SetDateObserverBiz} from "@/utils/biz/common/SetDateObserverBiz";
import LayerComps from "@/components/public/layer/scenes";
import {RoomOverObserverBiz} from "@/utils/biz/room/RoomOverObserverBiz";
import {WindowCommonObserverBiz} from "@/utils/biz/window/WindowCommonObserverBiz";
import {UserCommitApi} from "@/api/user_common";
import {ApiDataUtil} from "@/utils/biz/common/ApiDataUtil";

export default {
  name: "WindowScreen",

  props: {
    formJson: {
      widgetList: [],
      formConfig: {
        devType: true
      },
    },
    formConfig: {},
    formData: Object,
    templateInfo: {},
    // 0表示门诊 1 第三方 2 其他
    apiType: {
      type: Number,
      default: 0
    },
    optionData: {},
  },

  components: {
    VFormRender,
    ...LayerComps
  },

  data() {
    return {
      parentApi: this.createParentOptions(),
      deviceInfo: null,
      // 诊室屏 -- 相关数据
      roomScreenData: {
        // 顶部科室 诊室信息
        roomDeptInfo:{
          // 科室名称
          deptName:'',
          // 科室简称
          deptShortName:'',
          // 屏幕所属科室
          oldDeptName:'',
          oldDeptShortName:'',
          // 科室简介
          deptIntroduction:'',
          // 诊室名称
          roomName:'',
          // 诊室号
          roomNo:'',
          // 诊室简称
          roomShortName:''
        },
        //候诊类型--1候诊等候--2候诊列表
        waitPatientType: 1,
        //候诊列表截取的人数
        waitNum: 0,
        // 置空专用
        workerInfo: {
          workerId: "", // 医生ID
          workStationId: '',// 医生工作站ID
          workStationName: '',// 医生工作站
          registerObjIdList:[],
          workerName: "", // 医生姓名
          workerPicture: "", // 医生照片
          workerBusinessCard:'',// 医生二维码
          workerTitle: "", //医生职称
          workerIntro: "", //医生简介
          workerSpecialty: "",// 医生擅长
          isPause: false, // 暂停接诊状态
          onlineStatus:'',
          deptName:'', // 医生所属科室
          treatingPatient: {}, //正在就诊患者
          treatingPatientList: [], //正在就诊患者
          waitingPatientList: [] // 等候就诊患者
        },
        // 医生ID
        workerIdList: [],
        // 医生信息
        workerInfoList: [
          {
            workerId: "", // 医生ID
            workStationId: '',// 医生工作站ID
            workStationName: '',// 医生工作站
            registerObjIdList:[],
            workerName: "", // 医生姓名
            workerPicture: "", // 医生照片
            workerBusinessCard:'',// 医生二维码
            workerTitle: "", //医生职称
            workerIntro: "", //医生简介
            workerSpecialty: "",// 医生擅长
            deptName:'', // 医生所属科室
            isPause: false, // 暂停接诊状态
            onlineStatus:'',
            treatingPatient: {}, //正在就诊患者
            treatingPatientList: [], //正在就诊患者
            waitingPatientList: [] // 等候就诊患者
          }
        ],
      },

      // 组件缓存
      modelMap: {},
      // 缓存
      commonJsonMap: {},
      // 诊室屏 -- 弹窗
      msgWinData: {
        treatingAlert: true, // 是否显示就诊弹窗
        waitingAlert: true, // 是否显示候诊弹窗
        data:{},
        checkList:[1,3],
        currPatient: [],
        waitPatient: [],
        // 号别显示名称
        registerObjNameKey:'registerObjName',
        current:{
          content:'就诊'
        },
        waiting:{
          content:'候诊'
        },
        popupBackground:'',
        overlayBackground:'',
      },
      // 医生排班 name:'',
      workerSchedulingJson: {},
      eventBus: null,
      hasCallShow: false,

      isApiData:false,
      // 弹窗设置
      layerNameKey: "call-patient",
      // 暂停接诊
      pauseLayerInfo: {
        visible: false,
        info: {
          content:'暂停服务',
          fontSize: 388,
          color:'#ffffff',
          fontWeight:500
        }
      },
    };
  },

  mounted() {
    this.setRem();
    // 初始化
    this.init();
  },

  methods: {
    // 安卓报错信息的写入
    handleException(funcName, errType, errMsg) {
      AndroidSDK.writeLog(`${funcName}--${errType}-->${errMsg}`);
    },

    // 安卓正常写入日志
    handleWriteLog(funcName, msgContent) {
      AndroidSDK.writeLog(`${funcName}---->${msgContent}`);
    },

    /**
     * 安卓调用
     * @param obj
     */
    sdkServices(obj) {
      this.handleWriteLog("sdkServices", JSON.stringify(obj));
      try {
        if (obj.bizType && obj.bizType !== "") {
          switch (obj.bizType) {
            case "getDeviceInfoCallBack":
              this.deviceInfo = JSON.parse(resetLongToStr(obj.msgContent));
              this.initAfterGetDeviceInfo();
              break;
            case "webPing":
              AndroidSDK.androidPong();
              break;
            default:
              // 监听设置
              this.eventBus.$emit(obj.bizType, obj.msgContent);
          }
        } else {
          this.handleException("sdkServices", "数据错误", JSON.stringify(obj));
        }
      } catch (e) {
        this.handleException("sdkServices", "解析错误", JSON.stringify(obj));
      }
    },

    /**
     * 安卓调用
     * @param obj
     */
    sdkBizServices(obj) {
      this.handleWriteLog("sdkBizServices", JSON.stringify(obj));
      try {
        if (obj.bizType && obj.bizType !== "") {
          this.eventBus.$emit(obj.bizType, obj.msgContent);
        } else {
          this.handleException("sdkBizServices", "数据错误", JSON.stringify(obj));
        }
      } catch (e) {
        this.handleException("sdkBizServices", "解析错误", JSON.stringify(obj));
      }
    },

    /**
     * 初始化逻辑
     */
    init() {
      // 数据挂载
      parent.window.webSDKServices = this.sdkServices;
      parent.window.webSDKBizServices = this.sdkBizServices;
      AndroidSDK.androidPong();
      // 遍历数据 将模板数据存储到Map缓存中
      this.formJson.widgetList.forEach((item) => {
        this.modelMap[item.categoryType] = item;
      });
      // 设置接口中需要用的参数
      this.setParams();
      // 主题消息 Subject
      this.eventBus = new SubjectUtil();

      //获取终端信息
      AndroidSDK.getDeviceInfo();
    },
    /**
     * 初始化 模板参数
     */
    setParams() {
      // 加载主屏逻辑
      let mainInfo = this.modelMap["room-window"];
      if (mainInfo) {
        let configObj = mainInfo.options[mainInfo.options.config];
        //候诊类型--1 候诊等候--2 候诊列表  默认1
        this.roomScreenData.waitPatientType = configObj.waitPatientType || 1;
        //候诊列表截取的人数 为0 表示不查询 默认0 即使开启了候诊列表，这个之为0 也默认走等候逻辑
        this.roomScreenData.waitNum = configObj.waitPatientNumber || 0;
        // 等候隐藏，参数置为默认值
        if(true === configObj.waitingPatientHide){
          // 请求方式设置为候诊
          this.roomScreenData.waitPatientType = 1;
          // 等候人数为0
          this.roomScreenData.waitNum = 0;
        }

        // 模板中配置的号别KEY
        this.msgWinData.registerObjNameKey = configObj.registerObjNameKey || 'registerObjName';

        // 设置弹窗名称
        if(configObj.layerInfo && configObj.layerInfo.current){
          this.msgWinData.current = configObj.layerInfo.current || {content:'就诊'};
          // 颜色
          this.msgWinData.popupBackground = configObj.layerInfo.current.popupBackground || '';
          // 透明度
          this.msgWinData.overlayBackground = configObj.layerInfo.current.overlayBackground || '';

        }
        if(configObj.layerInfo && configObj.layerInfo.waiting){
          this.msgWinData.waiting = configObj.layerInfo.waiting || {content:'候诊'}
        }
        // 调用哪个弹窗
        this.layerNameKey = configObj.layerNameKey || 'call-patient';
        // 弹窗号别配置
        this.msgWinData.checkList = configObj.checkList || [1,3];

        // 特制消息标识
        this.msgRegisterMark = configObj.msgRegisterMark || '';
        // 有接口配置属性
        if(mainInfo.screenDataType.indexOf('ApiInfo')){
          // 是否配置接口
          this.isApiData = true;
        }
      }
    },
    /**
     * 获取设备信息后初始化
     */
    initAfterGetDeviceInfo() {
      // 特制消息清理+注册
      this.registerMsg();

      // 加载主屏逻辑
      let mainInfo = this.modelMap["room-window"];
      if (mainInfo) {
        let emp = new WindowCommonObserverBiz(this, this.deviceInfo, this.modelMap["room-window"]);
        this.eventBus.addObserver(emp);
        emp.init();
        // 窗口屏配置了 适配接口逻辑
        if(this.isApiData === true){
          let apiEmp = new ApiDataUtil(this, this.deviceInfo, this.modelMap["room-window"]);
          apiEmp.init();
        }
      }

      // 头部时间
      if (this.modelMap["header"]) {
        // 头部时间 - 观察者
        let emp = new SetDateObserverBiz(this, this.deviceInfo, this.modelMap["header"]);
        this.eventBus.addObserver(emp);
      }

      // 通用过号组件
      if (this.modelMap["pass-patient-common"]) {
        let tempData = this.modelMap["pass-patient-common"];
        // 过号 - 观察者
        let emp = new RoomOverObserverBiz(this, this.deviceInfo, tempData);
        this.eventBus.addObserver(emp);
        emp.getPassData();
      }

      // 获取多媒体
      this.getVideoMedias();

    },

    /**
     * 消息注册
     */
    async registerMsg() {
      // 特制消息存在才会注册
      try {
        // 注册消息
        const {code, data} = await UserCommitApi.bindTerminalBusinessFlag({
          terminalId: this.deviceInfo.screenId,
          terminalType: this.deviceInfo.screenType,
          businessFlag: this.msgRegisterMark
        })
      } catch (e) {
        this.handleException('sdkBizServices', '特制消息注册失败 -- registerMsg -- >', JSON.stringify(e.stack));
      }
    },

    /**
     * 适配2k 4k
     */
    setRem() {
      const {resolution} = this.templateInfo;
      if (resolution) {
        // 重新计算尺寸
        setRem2(19.2, resolution.split("*")[0]);
        window.onresize = function () {
          setRem2(19.2, resolution.split("*")[0]);
        };
      }
    },
    createParentOptions() {
      return {
        self: this,
        executeParentMethod(key, data) {
          switch (key) {
            case "writeLog":
              // 内部组件调用 诙谐LOG 日志
              this.self.handleWriteLog('sdkBizServices','内部组件打印日志 -- >',data || '')
              break
            case "playVideoMedias":
              // 获取视频组件位置 给安卓
              this.self.playVideoMedias(data);
              break;
          }
        },
      };
    },

    /**
     * 获取多媒体
     * @param data
     */
    getVideoMedias(data) {
      try {
        let roomItem = this.modelMap["room-window"];
        const formRef = this.$refs.vFormRef;
        if (formRef) {
          this.$refs.vFormRef.executeChildMethod(roomItem?.id, "getVideoMedias", data || {});
        }
      } catch (e) {
        this.handleException("sdkBizServices", "内部组件异常 -- getVideoMedias -- >", JSON.stringify(e.stack));
      }
    },

    /**
     * 获取 多媒体
     * @param obj
     */
    playVideoMedias(obj) {
      try {
        // resources:[{url: ''}]
        const {positionInfo, video} = obj;
        const {left, top, width, height} = positionInfo;
        const resources = [];
        video.forEach((item) => {
          resources.push({
            url: item.url
          });
        });
        AndroidSDK.playVideoMedias({
          x: left,
          y: top,
          width: width,
          height: height,
          type: "2",
          resources
        });
      } catch (e) {
        this.handleException("sdkBizServices", "获取多媒体数据解析失败", JSON.stringify(e.stack));
      }
    },

  }

};
</script>
